<?php
/**
 * Notes:
 * User: wudg <544038230@qq.com>
 * Date: 2025/4/1 11:29
 */

namespace App\Service\Socket;


use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;

class WebSocketService
{
    #[Inject]
    protected Redis $redis;


    protected $cacheSidPre ='socket:sid';
    protected $cacheUidPre ='socket:user';


    /**
     * 设置过期时间
     * @var int
     */
    protected $cacheTime = 86400;


    public function bindSidUid(string $sid,int $uid)
    {
        $this->redis->setex("{$this->cacheSidPre}:$sid",$this->cacheTime,$uid);
        $this->redis->sAdd("{$this->cacheUidPre}:{$uid}:sockets",$sid);
        $this->redis->expire("{$this->cacheUidPre}:{$uid}:sockets",$this->cacheTime);
    }


    /**
     * sid 获取uid
     * @param string $sid
     * @return bool|mixed|string
     */
    public function sidGetUid(string $sid)
    {
        return $this->redis->get("{$this->cacheSidPre}:$sid");
    }


    /**
     * uid 获取sid
     * @param int $uid
     * @return array
     */
    public function uidGetSid(int $uid)
    {
        return $this->redis->sMembers("{$this->cacheUidPre}:{$uid}:sockets");
    }

    public function clearSid(string $sid)
    {
        $uid = $this->redis->get("{$this->cacheSidPre}:$sid");
        if($uid)
        {
            $this->redis->del("{$this->cacheSidPre}:$sid");
            $this->redis->sRem("{$this->cacheUidPre}:{$uid}:sockets",$sid);
        }
    }


    public function userChatData(int $uid)
    {

    }


}